package com.jsh.erp.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.jsh.erp.constants.ExceptionConstants;
import com.jsh.erp.datasource.entities.*;
import com.jsh.erp.exception.BusinessRunTimeException;
import com.jsh.erp.service.depot.DepotService;
import com.jsh.erp.service.depotHead.DepotHeadService;
import com.jsh.erp.service.material.MaterialService;
import com.jsh.erp.service.redis.RedisService;
import com.jsh.erp.service.systemConfig.SystemConfigService;
import com.jsh.erp.service.user.UserService;
import com.jsh.erp.service.userBusiness.UserBusinessService;
import com.jsh.erp.utils.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.dao.DataAccessException;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.HandlerMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;

import static com.jsh.erp.utils.ResponseJsonUtil.returnJson;

/**
 * Description
 *
 * @Author: jishenghua
 * @Date: 2021-3-13 0:01
 */
@RestController
@RequestMapping(value = "/systemConfig")
@Api(tags = {"系统参数"})
public class SystemConfigController {
    private Logger logger = LoggerFactory.getLogger(SystemConfigController.class);

    @Resource
    private UserService userService;

    @Resource
    private DepotService depotService;

    @Resource
    private DepotHeadService depotHeadService;

    @Resource
    private UserBusinessService userBusinessService;

    @Resource
    private SystemConfigService systemConfigService;

    @Resource
    private RedisService redisService;

    @Value(value = "${file.path}")
    private String filePath;

    @Value(value = "${spring.servlet.multipart.max-file-size}")
    private Long maxFileSize;

    @Value(value = "${spring.servlet.multipart.max-request-size}")
    private Long maxRequestSize;
    @Resource
    private MaterialService materialService;
    @Value(value = "${all.url}")
    private String allUrl;
    @Value(value = "${material.url}")
    private String materialUrl;
    @Value(value = "${material.all.url}")
    private String materialAllUrl;
    @Value(value = "${material.info.url}")
    private String materialInfoUrl;
    @Value(value = "${Info.url}")
    private String infoUrl;
    @Value(value = "${allocation.url}")
    private String allocationUrl;
    @Value(value = "${update.flag.url}")
    private String updateFlagUrl;
    @Value(value = "${basic.url}")
    private String basicUrl;
    @Value(value = "${update.audit.url}")
    private String basicAuditUrl;
//    @Value(value = "${user.tenant.id}")
//    private String tenantId;

    private static final String tenantId = ResourcesUtil.getValue("TenantId", "user.tenant.id");
    /**
     * 获取当前租户的配置信息
     *
     * @param request
     * @return
     */
    @GetMapping(value = "/getCurrentInfo")
    @ApiOperation(value = "获取当前租户的配置信息")
    public BaseResponseInfo getCurrentInfo(HttpServletRequest request) throws Exception {
        BaseResponseInfo res = new BaseResponseInfo();
        String lanCode = redisService.getLanCodeFromSession(request);
        try {
            List<SystemConfig> list = systemConfigService.getSystemConfig();
            res.code = 200;
            if (list.size() > 0) {
                res.data = list.get(0);
            }
        } catch (Exception e) {
            e.printStackTrace();
            res.code = 500;
            res.data = "zh".equals(lanCode) ? ErpInfo.FAILED.name : ErpInfo.FAILED.lanCodeName;
        }
        return res;
    }

    /**
     * 获取文件大小限制
     *
     * @param request
     * @return
     * @throws Exception
     */
    @GetMapping(value = "/fileSizeLimit")
    @ApiOperation(value = "获取文件大小限制")
    public BaseResponseInfo fileSizeLimit(HttpServletRequest request) throws Exception {
        BaseResponseInfo res = new BaseResponseInfo();
        String lanCode = redisService.getLanCodeFromSession(request);
        try {
            Long limit = 0L;
            if (maxFileSize < maxRequestSize) {
                limit = maxFileSize;
            } else {
                limit = maxRequestSize;
            }
            res.code = 200;
            res.data = limit;
        } catch (Exception e) {
            e.printStackTrace();
            res.code = 500;
            res.data = "zh".equals(lanCode) ? ErpInfo.FAILED.name : ErpInfo.FAILED.lanCodeName;
        }
        return res;
    }

    /**
     * 文件上传统一方法
     *
     * @param request
     * @param response
     * @return
     */
    @PostMapping(value = "/upload")
    @ApiOperation(value = "文件上传统一方法")
    public BaseResponseInfo upload(HttpServletRequest request, HttpServletResponse response) {
        BaseResponseInfo res = new BaseResponseInfo();
        String lanCode = redisService.getLanCodeFromSession(request);
        try {
            String savePath = "";
            String bizPath = request.getParameter("biz");
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            MultipartFile file = multipartRequest.getFile("file");// 获取上传文件对象
            if (StringUtil.isEmpty(bizPath)) {
                bizPath = "";
            }
            String token = request.getHeader("X-Access-Token");
            String tenantId = Tools.getTenantIdByToken(token);
            bizPath = bizPath + File.separator + tenantId;
            savePath = this.uploadLocal(file, bizPath);
            if (StringUtil.isNotEmpty(savePath)) {
                res.code = 200;
                res.data = savePath;
            } else {
                res.code = 500;
                res.data = "zh".equals(lanCode) ? "上传失败！" : "fail to upload";
            }
        } catch (Exception e) {
            e.printStackTrace();
            res.code = 500;
            res.data = "zh".equals(lanCode) ? "上传失败！" : "fail to upload";
        }
        return res;
    }


    @PostMapping(value = "/uploadAttachment")
    @ApiOperation(value = "文件上传统一方法")
    public BaseResponseInfo uploadAttachment(HttpServletRequest request, HttpServletResponse response) {
        BaseResponseInfo res = new BaseResponseInfo();
        Attachment attachment = new Attachment();
        String lanCode = redisService.getLanCodeFromSession(request);
        String baseStr = null;
        try {
            String fileName=null;
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            MultipartFile multiPartFile = multipartRequest.getFile("file");// 获取上传文件对象
            baseStr = Base64.getEncoder().encodeToString(multiPartFile.getBytes());
            baseStr = baseStr.replaceAll("\r\n", "");

            attachment.setData(baseStr);
            String orgName = multiPartFile.getOriginalFilename();
            orgName = FileUtils.getFileName(orgName);
            if (orgName.indexOf(".") != -1) {
                fileName = orgName.substring(0, orgName.lastIndexOf(".")) + "_" + System.currentTimeMillis() + orgName.substring(orgName.indexOf("."));
            } else {
                fileName = orgName + "_" + System.currentTimeMillis();
            }
            if (!StringUtils.isEmpty(fileName)){
                attachment.setFileName(fileName);
            }
            attachment.setType(FileUtils.getFileExtendName(fileName));
            res.code = 200;
            res.data = attachment;
        } catch (Exception e) {
            e.printStackTrace();
            res.code = 500;
            res.data = "zh".equals(lanCode) ? "上传失败！" : "fail to upload";
        }
        return res;
    }

    /**
     * 本地文件上传
     *
     * @param mf      文件
     * @param bizPath 自定义路径
     * @return
     */
    private String uploadLocal(MultipartFile mf, String bizPath) {
        try {
            String ctxPath = filePath;
            String fileName = null;
            File file = new File(ctxPath + File.separator + bizPath + File.separator);
            if (!file.exists()) {
                file.mkdirs();// 创建文件根目录
            }
            String orgName = mf.getOriginalFilename();// 获取文件名
            orgName = FileUtils.getFileName(orgName);
            if (orgName.indexOf(".") != -1) {
                fileName = orgName.substring(0, orgName.lastIndexOf(".")) + "_" + System.currentTimeMillis() + orgName.substring(orgName.indexOf("."));
            } else {
                fileName = orgName + "_" + System.currentTimeMillis();
            }
            String savePath = file.getPath() + File.separator + fileName;
            File savefile = new File(savePath);
            FileCopyUtils.copy(mf.getBytes(), savefile);
            String dbpath = null;
            if (StringUtil.isNotEmpty(bizPath)) {
                dbpath = bizPath + File.separator + fileName;
            } else {
                dbpath = fileName;
            }
            if (dbpath.contains("\\")) {
                dbpath = dbpath.replace("\\", "/");
            }
            return dbpath;
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }
        return "";
    }

    /**
     * 预览图片&下载文件
     * 请求地址：http://localhost:8080/common/static/{financial/afsdfasdfasdf_1547866868179.txt}
     *
     * @param request
     * @param response
     */
    @GetMapping(value = "/static/**")
    @ApiOperation(value = "预览图片&下载文件")
    public void view(HttpServletRequest request, HttpServletResponse response) {
        // ISO-8859-1 ==> UTF-8 进行编码转换
        String imgPath = extractPathFromPattern(request);
        if (StringUtil.isEmpty(imgPath) || imgPath == "null") {
            return;
        }
        // 其余处理略
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            imgPath = imgPath.replace("..", "");
            if (imgPath.endsWith(",")) {
                imgPath = imgPath.substring(0, imgPath.length() - 1);
            }
            String fileUrl = filePath + File.separator + imgPath;
            File file = new File(fileUrl);
            if (!file.exists()) {
                response.setStatus(404);
                throw new RuntimeException("文件不存在..");
            }
            response.setContentType("application/force-download");// 设置强制下载不打开
            response.addHeader("Content-Disposition", "attachment;fileName=" + new String(file.getName().getBytes("UTF-8"), "iso-8859-1"));
            inputStream = new BufferedInputStream(new FileInputStream(fileUrl));
            outputStream = response.getOutputStream();
            byte[] buf = new byte[1024];
            int len;
            while ((len = inputStream.read(buf)) > 0) {
                outputStream.write(buf, 0, len);
            }
            response.flushBuffer();
        } catch (IOException e) {
            logger.error("预览文件失败" + e.getMessage());
            response.setStatus(404);
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    logger.error(e.getMessage(), e);
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    logger.error(e.getMessage(), e);
                }
            }
        }
    }

    /**
     * 把指定URL后的字符串全部截断当成参数
     * 这么做是为了防止URL中包含中文或者特殊字符（/等）时，匹配不了的问题
     *
     * @param request
     * @return
     */
    private static String extractPathFromPattern(final HttpServletRequest request) {
        String path = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
        String bestMatchPattern = (String) request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
        return new AntPathMatcher().extractPathWithinPattern(bestMatchPattern, path);
    }


    /**
    * @Author: wy
    * @Description: 上传所有
    * @DateTime: 2022-08-23 15:36
    * @Params:
    * @Return
    */
    @GetMapping(value = "/getNewJsonObject",produces = "application/json;charset=UTF-8")
    @ApiOperation(value = "门店同步到总仓-所有数据和单据")
    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public String getNewJsonObject(HttpServletRequest request,@RequestParam(value = "syncType", required = false)@ApiParam("1-外网 2-内网") String syncType) throws Exception {
        String data=null;
        //获取主仓地址
        User user = userService.getManager();
        if (user != null) {
            String remark=null;
           if ("1".equals(syncType)){
               if (StringUtil.isNotEmpty(user.getDescription())){
                   remark=user.getDescription();
               }else {
                   String lanCode = redisService.getLanCodeFromSession(request);
                   throw new BusinessRunTimeException(ExceptionConstants.USER_SYNC_OUTER_FAILED_CODE,
                           "zh".equals(lanCode) ? ExceptionConstants.USER_SYNC_OUTER_FAILED_MSG : ExceptionConstants.USER_SYNC_OUTER_FAILED_MSG_US);
               }
           }else  if ("2".equals(syncType)){
               if (StringUtil.isNotEmpty(user.getRemark())){
                   remark=user.getRemark();
               }else {
                   String lanCode = redisService.getLanCodeFromSession(request);
                   throw new BusinessRunTimeException(ExceptionConstants.USER_SYNC_INNER_FAILED_CODE,
                           "zh".equals(lanCode) ? ExceptionConstants.USER_SYNC_INNER_FAILED_MSG : ExceptionConstants.USER_SYNC_INNER_FAILED_MSG_US);
               }
           }
            if (StringUtils.isNotEmpty(remark)){
                logger.info("============同步方法 begin 调用开始==============");
//                上传所有
                String url=remark+allUrl;
                JSONObject jsonObject = systemConfigService.getTaskNewJsonObject();
                System.out.println("上传"+jsonObject.toJSONString());
                data = NoticeUtil.sendPost(url,jsonObject);
                JSONObject dataJSON=JSONObject.parseObject(data);
                Integer code = (Integer)dataJSON.get("code");
                if (code != null && code ==200){
                    systemConfigService.updateTaskNewJsonUploadFlag(jsonObject);
                }
                logger.info("============上传数据完成==============");
                //下拉基础数据
                JSONObject newJsonObject = new JSONObject();
                String baseUrl=remark+basicUrl+"?tenantId="+tenantId+"&flag="+true;
                String baseJsonObject = GetUtil.get(baseUrl);
                if (!StringUtils.isEmpty(baseJsonObject)){
                    newJsonObject = JSONObject.parseObject(baseJsonObject);
                }
                systemConfigService.synchronizationBasicData(newJsonObject,true);
                logger.info("============下拉数据完成==============");
                //下拉调拨
                JSONObject dbNewJsonObject = new JSONObject();
                List<String> idListString = systemConfigService.getTenantDepotIdList();
                String idList = StringUtil.listToString(idListString);
                String dbUrl=remark+infoUrl+"?idList="+idList;
                String dbJsonObject = GetUtil.get(dbUrl);
                if (!StringUtils.isEmpty(dbJsonObject)){
                    dbNewJsonObject = JSONObject.parseObject(dbJsonObject);
                }
                systemConfigService.synchronizationAllocation(dbNewJsonObject,request);
                //修改办公室下发的采购订单、厂家直发、盘点单，其它出入库的状态
                String upFlagUrl=remark+updateFlagUrl;
                NoticeUtil.sendPost(upFlagUrl,dbNewJsonObject);
                logger.info("============下拉调拨相关完成==============");
                //上传调拨
                String upUrl=remark+allocationUrl;
                JSONObject upJsonObject = systemConfigService.getUpInfoNewJsonObject();
                String allocationData = NoticeUtil.sendPost(upUrl, upJsonObject);
                JSONObject allocationDataJSON=JSONObject.parseObject(allocationData);
                Integer allocationCode = (Integer)allocationDataJSON.get("code");
                if (allocationCode !=null && allocationCode==200){
                    systemConfigService.updateAllocationUploadFlag(upJsonObject);
                }
                logger.info("============上传调拨完成==============");
                logger.info("============同步方法 end 调用结束 ==============");

            }else {
                String lanCode = redisService.getLanCodeFromSession(request);
                throw new BusinessRunTimeException(ExceptionConstants.USER_SYNC_FAILED_CODE,
                        "zh".equals(lanCode) ? ExceptionConstants.USER_SYNC_FAILED_MSG : ExceptionConstants.USER_SYNC_FAILED_MSG_US);
            }
        }

        return data;
    }
    @GetMapping(value = "/getBasicData")
    @ApiOperation(value = "需同步基础资料")
    public JSONObject getBasicData(HttpServletRequest request,@RequestParam("tenantId") String tenantId,@RequestParam("flag") boolean flag) throws Exception {
        return systemConfigService.getBasicData(tenantId,flag);
    }
    @PostMapping(value = "/synchronization",produces = "application/json;charset=UTF-8")
    @ApiOperation(value = "同步-不调用")
    public String synchronization(@RequestBody JSONObject obj,HttpServletRequest request) throws Exception {
        Map<String, Object> objectMap = new HashMap<>();
        String lanCode = redisService.getLanCodeFromSession(request);
        systemConfigService.synchronization(obj);
        System.out.println("上传"+obj.toJSONString());
        return returnJson(objectMap, "zh".equals(lanCode) ? ErpInfo.OK.name : ErpInfo.OK.lanCodeName, ErpInfo.OK.code);
    }

    @PostMapping(value = "/synchronizationUpAllocation",produces = "application/json;charset=UTF-8")
    @ApiOperation(value = "同步调拨-不调用")
    public String synchronizationAllocation(@RequestBody JSONObject obj,HttpServletRequest request) throws Exception {
        Map<String, Object> objectMap = new HashMap<>();
        String lanCode = redisService.getLanCodeFromSession(request);
        systemConfigService.synchronizationUpAllocation(obj);
        return returnJson(objectMap, "zh".equals(lanCode) ? ErpInfo.OK.name : ErpInfo.OK.lanCodeName, ErpInfo.OK.code);
    }

    @PostMapping(value = "/updatePurchaseUploadFlag",produces = "application/json;charset=UTF-8")
    @ApiOperation(value = "修改办公室下发的采购订单、厂家直发、盘点单，其它出入库的状态")
    public String updatePurchaseUploadFlag(@RequestBody JSONObject obj,HttpServletRequest request) throws Exception {
        Map<String, Object> objectMap = new HashMap<>();
        String lanCode = redisService.getLanCodeFromSession(request);
        systemConfigService.updatePurchaseUploadFlag(obj);
        return returnJson(objectMap, "zh".equals(lanCode) ? ErpInfo.OK.name : ErpInfo.OK.lanCodeName, ErpInfo.OK.code);
    }




   /**`
   * @Author: wy
   * @Description: 下载关于自己的所有
   * @DateTime: 2022-08-23 15:37
   * @Params:
   * @Return
   */

    @GetMapping(value = "/synchronizationStore",produces = "application/json;charset=UTF-8")
    @ApiOperation(value = "同步总仓信息")
    public String synchronizationStore(HttpServletRequest request) throws Exception {
        Map<String, Object> objectMap = new HashMap<>();
        //对比分仓的商品
        User user = userService.getManager();
        String lanCode = redisService.getLanCodeFromSession(request);
        if (user != null) {
            String remark = user.getRemark();
            JSONObject newJsonObject = new JSONObject();
            if (StringUtils.isNotEmpty(remark)){
                String token = request.getHeader("X-Access-Token");
                String tenantId = Tools.getTenantIdByToken(token);
                String url=remark+materialAllUrl+"?tenantId="+tenantId;
                String jsonObject = GetUtil.get(url);
                if (!StringUtils.isEmpty(jsonObject)){
                    newJsonObject = JSONObject.parseObject(jsonObject);
                }
                 systemConfigService.synchronizationStore(newJsonObject,tenantId);
            }else {
                throw new BusinessRunTimeException(ExceptionConstants.USER_SYNC_FAILED_CODE,
                        "zh".equals(lanCode) ? ExceptionConstants.USER_SYNC_FAILED_MSG : ExceptionConstants.USER_SYNC_FAILED_MSG_US);
            }
        }
       return returnJson(objectMap, "zh".equals(lanCode) ? ErpInfo.OK.name : ErpInfo.OK.lanCodeName, ErpInfo.OK.code);
    }

    @GetMapping(value = "/getMaterialNewJsonObject",produces = "application/json;charset=UTF-8")
    @ApiOperation(value = "门店同步到总仓-不调用")
    public JSONObject getMaterialNewJsonObject(@RequestParam("tenantId") String tenantId,HttpServletRequest request) throws Exception {

        return systemConfigService.getMaterialNewJsonObject(tenantId);
    }

    /**
     * @Author: wy
     * @Description: 下载新商品和新调拨相关
     * @DateTime: 2022-08-23 15:37
     * @Params:
     * @Return
     */

    @GetMapping(value = "/synchronizationMaterial",produces = "application/json;charset=UTF-8")
    @ApiOperation(value = "同步新商品和新调拨")
    public String synchronizationMaterial(HttpServletRequest request) throws Exception {
        Map<String, Object> objectMap = new HashMap<>();
        String lanCode = redisService.getLanCodeFromSession(request);
        //对比分仓的商品
        User user = userService.getManager();
        if (user != null) {
            String remark = user.getRemark();
            JSONObject newJsonObject = new JSONObject();
            if (StringUtils.isNotEmpty(remark)){
                List<String> idListString = depotService.getAnotherDepotIdList();
                String idList = StringUtil.listToString(idListString);
                String token = request.getHeader("X-Access-Token");
                String tenantId = Tools.getTenantIdByToken(token);
                String url=remark+materialInfoUrl+"?idList="+idList;
                String jsonObject = GetUtil.get(url);
                if (!StringUtils.isEmpty(jsonObject)){
                    newJsonObject = JSONObject.parseObject(jsonObject);
                }
                systemConfigService.synchronizationMaterial(newJsonObject,tenantId);
            }else {
                throw new BusinessRunTimeException(ExceptionConstants.USER_SYNC_FAILED_CODE,
                        "zh".equals(lanCode) ? ExceptionConstants.USER_SYNC_FAILED_MSG:ExceptionConstants.USER_SYNC_FAILED_MSG_US);
            }
        }
        return returnJson(objectMap, "zh".equals(lanCode) ? ErpInfo.OK.name : ErpInfo.OK.lanCodeName, ErpInfo.OK.code);
    }

    @GetMapping(value = "/getMaterialInfoNewJsonObject",produces = "application/json;charset=UTF-8")
    @ApiOperation(value = "获取新商品和新调拨")
    public JSONObject getMaterialInfoNewJsonObject(@RequestParam("idList") String idList,HttpServletRequest request) throws Exception {
        List<String> strings=null;
        if (StringUtils.isNotEmpty(idList)) {
            strings = StringUtil.strToStringList(idList);
        }
        return systemConfigService.getMaterialInfoNewJsonObject(strings);
    }

    @GetMapping(value = "/getInfoNewJsonObject",produces = "application/json;charset=UTF-8")
    @ApiOperation(value = "需同步调拨")
    public JSONObject getInfoNewJsonObject(@RequestParam("idList") String idList,HttpServletRequest request) throws Exception {
        List<String> strings=null;
        if (StringUtils.isNotEmpty(idList)) {
            strings = StringUtil.strToStringList(idList);
        }
        return systemConfigService.getInfoNewJsonObject(strings);
    }


    /**
    * @Author: wy
    * @Description: 新商品和新调拨提醒
    * @DateTime: 2022-08-23 15:37
    * @Params:
    * @Return
    */
    @GetMapping(value = "/getNewMaterial")
    @ApiOperation(value = "获取总仓新商品和新调拨信息")
    public JSONObject getNewMaterial(@RequestParam("idList") String idList,HttpServletRequest request) throws Exception {
        JSONObject newJsonObject = new JSONObject();
//        List<Material> materials = materialService.getMaterial();
//        newJsonObject.put("materials",materials);
        List<String> strings=null;
        if (StringUtils.isNotEmpty(idList)) {
             strings = StringUtil.strToStringList(idList);
        }
        List<DepotHead> applyDepotHead = depotHeadService.getDepotHeadWithSubType("要货申请",strings);
        newJsonObject.put("applyDepotHead",applyDepotHead);
        List<DepotHead> deliveryDepotHead = depotHeadService.getDepotHeadWithSubType("配送",strings);
        newJsonObject.put("deliveryDepotHead",deliveryDepotHead);
        return newJsonObject;
    }

    @GetMapping(value = "/getNewMaterialNotIn",produces = "application/json;charset=UTF-8")
    @ApiOperation(value = "对比分仓和总仓的商品，新商品和新调拨添加消息提醒")
    public void getNewMaterialNotIn(HttpServletRequest request) throws Exception {
        //对比分仓的商品
        User user = userService.getManager();
        String lanCode = redisService.getLanCodeFromSession(request);
        if (user != null) {
            String remark = user.getRemark();
            List<Material> materials=null;
            List<DepotHead> applyDepotHead=null;
            List<DepotHead> deliveryDepotHead=null;
            JSONObject newJsonObject = new JSONObject();
            if (StringUtils.isNotEmpty(remark)){
                List<String> idListString = depotService.getAnotherDepotIdList();
                String idList = StringUtil.listToString(idListString);
                String url=remark+materialUrl+"?idList="+idList;
                String jsonObject = GetUtil.get(url);
                if (!StringUtils.isEmpty(jsonObject)){
                    newJsonObject = JSONObject.parseObject(jsonObject);
                }
//                materials = JSONObject.parseArray(newJsonObject.getJSONArray("materials").toJSONString(), Material.class);
//                if (null!=materials && materials.size()>0){
//                    materialService.checkIsMaterialIdList(materials);
//                }
                applyDepotHead = JSONObject.parseArray(newJsonObject.getJSONArray("applyDepotHead").toJSONString(), DepotHead.class);
                if (null!=applyDepotHead && applyDepotHead.size()>0){
                    depotHeadService.checkIsDepotHeadIdList(applyDepotHead,"要货申请");
                }
                deliveryDepotHead = JSONObject.parseArray(newJsonObject.getJSONArray("deliveryDepotHead").toJSONString(), DepotHead.class);
                if (null!=deliveryDepotHead && deliveryDepotHead.size()>0){
                    depotHeadService.checkIsDepotHeadIdList(deliveryDepotHead,"配送");
                }
            }else {
                throw new BusinessRunTimeException(ExceptionConstants.USER_SYNC_FAILED_CODE,
                        "zh".equals(lanCode) ? ExceptionConstants.USER_SYNC_FAILED_MSG:ExceptionConstants.USER_SYNC_FAILED_MSG_US);
            }
        }
    }

//    @GetMapping(value = "/getMaterialNewJsonObject")
//    @ApiOperation(value ="要货订单同步")
//    public List<> getMaterialNewJsonObject(HttpServletRequest request) throws Exception {
//        JSONObject jsonObject = systemConfigService.getNewJsonObject();
//        String s = NoticeUtil.sendPost(jsonObject);
//        return s;
//    }
}
